import { defineStore } from 'pinia'
import { mockCategories, mockLocations, mockStatuses } from '../mock'
import { itemService, categoryService, locationService, statusService } from '../utils/fallbackService'
import { ElMessage } from 'element-plus'
import { messageHelper } from '../utils/messageHelper'

export const useItemsStore = defineStore('items', {
    state: () => ({
        items: [],
        locations: mockLocations,
        categories: mockCategories,
        statuses: mockStatuses,
        loading: false,
        error: null,
        dataSource: 'unknown', // 'api' 或 'mock'
        pagination: {
            currentPage: 1,
            pageSize: 12, // 修改默认每页数量为12
            total: 0,
            totalPages: 0
        },
        filters: {
            categoryId: null,
            locationId: null,
            status: null,
            search: '',
            sortBy: 'name',
            sortOrder: 'asc'
        },
        rawResponse: null
    }),

    getters: {
        getItemsByLocation: (state) => (locationId) => {
            return state.items.filter(item => item.locationId === locationId);
        },
        getItemsByCategory: (state) => (categoryId) => {
            return state.items.filter(item => item.categoryId === categoryId);
        },
        getItemsByStatus: (state) => (status) => {
            return state.items.filter(item => item.status === status);
        },
        getTotalItemsCount: (state) => state.items.length,
        getItemById: (state) => async (id) => {
            state.loading = true;
            try {
                const result = await itemService.getItem(id);
                state.dataSource = result.source;
                if (result.source === 'mock' && result.error) {
                    ElMessage.warning(`无法连接到后端服务，使用本地数据: ${result.error}`);
                }
                return result.data;
            } catch (error) {
                console.error('获取物品详情失败', error);
                return null;
            } finally {
                state.loading = false;
            }
        },
        getFilteredItems: (state) => {
            // 检查是否有原始响应数据并且来源是API
            if (state.dataSource === 'api' && state.rawResponse) {
                // 使用保存的原始响应数据
                console.log("从rawResponse返回数据:", state.rawResponse);
                return state.rawResponse;
            }

            // 否则走原来的过滤逻辑
            let filtered = [...state.items];

            // 按位置筛选
            if (state.filters.locationId !== null) {
                filtered = filtered.filter(item => item.locationId === state.filters.locationId);
            }

            // 按分类筛选
            if (state.filters.categoryId !== null) {
                filtered = filtered.filter(item => item.categoryId === state.filters.categoryId);
            }

            // 按状态筛选
            if (state.filters.status !== null) {
                filtered = filtered.filter(item => item.status === state.filters.status);
            }

            // 按搜索关键字筛选 (名称或备注)
            if (state.filters.search) {
                const searchTerm = state.filters.search.toLowerCase();
                filtered = filtered.filter(item =>
                    (item.name && item.name.toLowerCase().includes(searchTerm)) ||
                    (item.notes && item.notes.toLowerCase().includes(searchTerm))
                );
            }

            // 排序
            if (state.filters.sortBy) {
                filtered.sort((a, b) => {
                    const fieldA = a[state.filters.sortBy];
                    const fieldB = b[state.filters.sortBy];

                    let comparison = 0;
                    if (fieldA > fieldB) {
                        comparison = 1;
                    } else if (fieldA < fieldB) {
                        comparison = -1;
                    }

                    return state.filters.sortOrder === 'desc' ? (comparison * -1) : comparison;
                });
            }

            return filtered;
        },
        getCategoryName: (state) => (id) => {
            const category = state.categories.find(c => c.id === id);
            return category ? category.name : '';
        },
        getLocationName: (state) => (id) => {
            const location = state.locations.find(l => l.id === id);
            return location ? location.name : '';
        },
        getStatusName: (state) => (value) => {
            const status = state.statuses.find(s => s.value === value);
            return status ? status.name : '';
        },
        getIconCategory: () => (iconId) => {
            const icons = [
                { id: 1, name: 'box', category: '基础图标', label: '盒子' },
                { id: 2, name: 'folder', category: '基础图标', label: '文件夹' },
                { id: 3, name: 'calendar', category: '基础图标', label: '日历' },
                { id: 4, name: 'star', category: '基础图标', label: '收藏星星' },
                { id: 5, name: 'folder', category: '基础图标', label: '文件夹' },
                // 数码
                { id: 10, name: 'smartphone', category: '数码', label: '智能手机' },
                { id: 11, name: 'laptop', category: '数码', label: '笔记本电脑' },
                { id: 12, name: 'tablet', category: '数码', label: '平板电脑' },
                { id: 13, name: 'phone', category: '数码', label: '手机' },
                // 首饰
                { id: 20, name: 'ring', category: '首饰', label: '戒指' },
                { id: 21, name: 'necklace', category: '首饰', label: '项链' },
                { id: 22, name: 'bracelet', category: '首饰', label: '手镯' },
                // 美妆
                { id: 30, name: 'mirror', category: '美妆', label: '镜子' },
                { id: 31, name: 'cream', category: '美妆', label: '面霜' },
                { id: 32, name: 'comb', category: '美妆', label: '梳子' },
                // 厨具
                { id: 33, name: 'bowl', category: '厨具', label: '碗' },
                { id: 34, name: 'chopsticks', category: '厨具', label: '筷子' },
                { id: 35, name: 'spoon', category: '厨具', label: '勺子' },
                // 工具
                { id: 43, name: 'hammer', category: '工具', label: '锤子' },
                { id: 44, name: 'screwdriver', category: '工具', label: '螺丝刀' },
                { id: 45, name: 'pliers', category: '工具', label: '钳子' },
                // 玩具
                { id: 53, name: 'blocks', category: '玩具', label: '积木' },
                { id: 54, name: 'puzzle', category: '玩具', label: '拼图' },
                { id: 55, name: 'rocket', category: '玩具', label: '火箭' },
                { id: 56, name: 'robot', category: '玩具', label: '机器人' },
                { id: 57, name: 'teddy-bear', category: '玩具', label: '泰迪熊' },
                // 运动
                { id: 63, name: 'basketball', category: '运动', label: '篮球' },
                { id: 64, name: 'football', category: '运动', label: '足球' },
                { id: 65, name: 'baseball', category: '运动', label: '棒球' },
                // 家电
                { id: 73, name: 'refrigerator', category: '家电', label: '冰箱' },
                { id: 74, name: 'washing-machine', category: '家电', label: '洗衣机' },
                { id: 75, name: 'microwave', category: '家电', label: '微波炉' },
                // 交通
                { id: 85, name: 'car', category: '交通', label: '汽车' },
                { id: 86, name: 'bus', category: '交通', label: '公交车' },
                { id: 87, name: 'truck', category: '交通', label: '卡车' },
                // 服饰
                { id: 95, name: 'clothes', category: '服饰', label: '衣服' },
                { id: 96, name: 'tshirt', category: '服饰', label: 'T恤' },
                { id: 97, name: 'pants', category: '服饰', label: '裤子' }
            ]
            const icon = icons.find(icon => icon.id === iconId)
            return icon ? icon.category : null
        },
        getCategoryIdByIconCategory: (state) => (iconCategory) => {
            // 由于物品分类名称已与图标分类名称一致，直接按名称查找 ID
            const category = state.categories.find(c => c.name === iconCategory);
            // 如果找不到（例如 "基础图标" 可能不在物品分类中，或传入了无效分类），可以返回 null 或某个默认 ID
            return category ? category.id : null; // 或者返回 ID 为 1 的 "基础图标" ID
        }
    },

    actions: {
        async initData() {
            this.loading = true;
            this.error = null;
            try {
                await Promise.all([
                    this.fetchCategories(),
                    this.fetchStatuses()
                ]);
                // dataSource 的状态会在各自的 fetch 方法中根据 itemService 的返回来设置
                // 此处不再统一设置 dataSource
                console.log('基础数据（分类、位置、状态）初始化完成');
            } catch (error) {
                this.error = error.message || '初始化基础数据失败';
                // ElMessage.error(this.error); // 不在此处弹窗，由调用方处理
                console.error('Store: initData 失败', error);
                // 即使失败，mock数据已在state中定义，fallbackService会处理
                // 确保 dataSource 反映真实情况 (如果部分成功部分失败会比较复杂，目前依赖 fallbackService)
                throw error; // 将错误抛出，让调用者决定如何处理
            } finally {
                this.loading = false;
            }
        },

        // 清除缓存的方法，用于位置切换等场景
        clearCache() {
            this.items = []
            this.loading = false
            this.error = null
            this.rawResponse = null
            this.pagination = {
                currentPage: 1,
                pageSize: 12,
                total: 0,
                totalPages: 0
            }
            // 保留过滤条件中的locationId，清除其他过滤条件
            const locationId = this.filters.locationId
            this.filters = {
                categoryId: null,
                locationId: locationId, // 保留位置ID
                status: null,
                search: '',
                sortBy: 'name',
                sortOrder: 'asc'
            }
            console.log('物品缓存已清除, 保留位置ID:', locationId)
        },

        setFilters(filters) {
            this.filters = { ...this.filters, ...filters };
            this.pagination.currentPage = 1; // 重置到第一页
            this.fetchItems();
        },

        setPage(page) {
            this.pagination.currentPage = page;
            this.fetchItems();
        },

        setPageSize(size) {
            this.pagination.pageSize = size;
            this.pagination.currentPage = 1; // 重置到第一页
            this.fetchItems();
        },

        // 添加新方法：加载更多物品（无限滚动）
        async loadMoreItems(nextPage) {
            // 不显示全局loading状态，因为我们只想在底部显示加载中
            this.error = null;
            try {
                console.log('Store: 加载更多物品, 页码:', nextPage);
                console.log('当前过滤条件:', JSON.stringify({
                    categoryId: this.filters.categoryId,
                    locationId: this.filters.locationId,
                    specificLocation: this.filters.locationId ? this.getLocationName(this.filters.locationId) : null,
                    status: this.filters.status,
                    search: this.filters.search,
                    sortBy: this.filters.sortBy,
                    sortOrder: this.filters.sortOrder,
                    page: nextPage,
                    pageSize: this.pagination.pageSize
                }));

                // 创建一个会在10秒后超时的Promise
                const timeoutPromise = new Promise((_, reject) => {
                    setTimeout(() => reject(new Error('请求超时，可能是网络问题')), 10000);
                });

                // 验证页码参数
                if (!nextPage || typeof nextPage !== 'number' || nextPage < 1) {
                    throw new Error(`无效的页码: ${nextPage}`);
                }

                // 与正常的API请求竞争
                console.log('Store: 发起API请求');
                let result;
                try {
                    result = await Promise.race([
                        itemService.getItems({
                            categoryId: this.filters.categoryId,
                            locationId: this.filters.locationId,
                            specificLocation: this.filters.locationId ? this.getLocationName(this.filters.locationId) : null,
                            status: this.filters.status,
                            search: this.filters.search,
                            sortBy: this.filters.sortBy,
                            sortOrder: this.filters.sortOrder,
                            page: nextPage,
                            pageSize: this.pagination.pageSize
                        }),
                        timeoutPromise
                    ]);
                } catch (requestError) {
                    console.error('API请求失败:', requestError);
                    throw new Error(`API请求失败: ${requestError.message}`);
                }

                console.log('Store: API请求已完成，状态:', result ? '成功' : '失败');
                console.log('响应结果:', JSON.stringify(result));

                // 确保结果中有items数组
                if (!result.items || !Array.isArray(result.items)) {
                    console.error('获取到的结果没有items数组:', result);
                    return false;
                }

                console.log(`Store: 获取到${result.items.length}个新物品`);

                // 将新加载的物品合并到现有列表中
                this.items = [...this.items, ...result.items];
                console.log(`Store: 合并后共有${this.items.length}个物品`);

                // 确保数据响应式更新
                if (this.rawResponse) {
                    if (Array.isArray(this.rawResponse.items)) {
                        this.rawResponse.items = [...this.rawResponse.items, ...result.items];
                        console.log(`Store: 更新了rawResponse中的items数组，现有${this.rawResponse.items.length}个物品`);
                    } else {
                        console.warn('Store: rawResponse没有items数组，无法合并数据');
                    }
                }

                this.dataSource = result.source;
                this.pagination = {
                    ...this.pagination,
                    currentPage: nextPage,
                    ...result.pagination
                };
                console.log('Store: 更新了分页信息:', JSON.stringify(this.pagination));

                // 如果使用的是模拟数据，显示警告
                if (result.source === 'mock' && result.error) {
                    console.warn(`无法连接到后端服务，使用本地数据: ${result.error}`);
                }

                return true;
            } catch (error) {
                console.error('Store: 加载更多物品失败:', error);
                console.error('错误堆栈:', error.stack);
                this.error = error.message || '加载更多物品失败';
                ElMessage.error(this.error);
                return false;
            }
        },

        async fetchItems() {
            this.loading = true;
            this.error = null;
            try {
                // 首先尝试从URL查询参数获取位置ID
                const locationIdFromUrl = window.location.search
                    .substring(1)
                    .split('&')
                    .map(param => param.split('='))
                    .find(param => param[0] === 'locationId');

                let locationId = locationIdFromUrl ? decodeURIComponent(locationIdFromUrl[1]) : null;
                console.log('从URL获取位置ID:', locationId);

                // 如果URL中没有位置ID，则尝试从localStorage获取
                if (!locationId) {
                    locationId = localStorage.getItem('currentLocationId');
                    console.log('从localStorage获取位置ID:', locationId);
                }

                // 如果仍未找到，则使用filters中的locationId
                if (!locationId && this.filters.locationId) {
                    locationId = this.filters.locationId;
                    console.log('使用filters中的位置ID:', locationId);
                }

                // 如果未设置位置ID，则记录警告
                if (!locationId) {
                    console.warn('未找到当前位置ID，请求所有物品数据');
                } else {
                    console.log('fetchItems使用位置ID:', locationId, '类型:', typeof locationId);
                }

                const result = await itemService.getItems({
                    categoryId: this.filters.categoryId,
                    locationId: locationId, // 使用上面获取的locationId
                    specificLocation: locationId ? this.getLocationName(locationId) : null, // 为兼容性保留
                    status: this.filters.status,
                    search: this.filters.search,
                    sortBy: this.filters.sortBy,
                    sortOrder: this.filters.sortOrder,
                    page: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize
                });

                // 打印接收到的结果
                console.log("从itemService.getItems接收到的结果:", result);

                // 更新数据及来源
                // 保存原始响应数据，方便计算属性处理
                if (result.source === 'api') {
                    // 将原始的 records 数组数据保存到 items
                    this.items = result.items;

                    // 同时保存完整的原始响应结构到 rawResponse
                    this.rawResponse = result;
                } else {
                    // 如果是模拟数据，按原来方式处理
                    this.items = result.items;
                }

                this.dataSource = result.source;
                this.pagination = {
                    ...this.pagination,
                    ...result.pagination
                };

                // 如果使用的是模拟数据，显示警告
                if (result.source === 'mock' && result.error) {
                    ElMessage.warning(`无法连接到后端服务，使用本地数据: ${result.error}`);
                }
            } catch (error) {
                this.error = error.message || '获取物品列表失败';
                ElMessage.error(this.error);
                console.error('fetchItems出错:', error);
            } finally {
                this.loading = false;
            }
        },

        // 获取所有物品数据（不分页）
        async fetchAllItems(locationId) {
            this.loading = true;
            this.error = null;
            try {
                const result = await itemService.getAllItems(locationId);

                if (result.success) {
                    this.items = result.items;
                    this.dataSource = result.source;

                    // 如果使用的是模拟数据，显示警告
                    if (result.source === 'mock' && result.error) {
                        ElMessage.warning(`无法连接到后端服务，使用本地数据: ${result.error}`);
                    }

                    return result.items;
                }
            } catch (error) {
                this.error = error.message || '获取所有物品数据失败';
                ElMessage.error(this.error);
                return [];
            } finally {
                this.loading = false;
            }
        },

        async fetchCategories() {
            try {
                const result = await categoryService.getCategories();
                if (result.success) {
                    this.categories = result.data;
                    this.dataSource = result.source;
                    if (result.source === 'mock' && result.error) {
                        ElMessage.warning(`无法连接到后端服务，使用本地分类数据`);
                    }
                }
            } catch (error) {
                console.error('获取分类失败', error);
            }
        },


        async fetchStatuses() {
            try {
                const result = await statusService.getStatuses();
                if (result.success) {
                    this.statuses = result.data;
                    this.dataSource = result.source;
                    if (result.source === 'mock' && result.error) {
                        ElMessage.warning(`无法连接到后端服务，使用本地状态数据`);
                    }
                }
            } catch (error) {
                console.error('获取状态失败', error);
            }
        },

        async addItem(itemData) {
            try {
                let itemToSend = { ...itemData };

                // 删除 isFavorite 字段
                if ('isFavorite' in itemToSend) {
                    delete itemToSend.isFavorite;
                    console.log('从请求体中删除 isFavorite 字段');
                }

                // 添加userId到请求体
                const userId = localStorage.getItem('userId');
                if (userId) {
                    itemToSend.userId = parseInt(userId) || userId; // 尝试转换为整数，如果失败则使用原始字符串
                    console.log('添加userId到请求体:', itemToSend.userId);
                } else {
                    console.warn('无法从localStorage获取userId，请求体中将不包含userId');
                    // 根据实际需求，如果userId是必需的，这里可以抛出错误或阻止请求
                    // ElMessage.error('无法获取用户信息，请重新登录。');
                    // return { success: false, message: '无法获取用户信息' };
                }

                console.log('开始添加物品，转换后发送的数据:', JSON.stringify(itemToSend));

                // 确保物品数据包含分类ID
                if (!itemToSend.categoryId) {
                    if (this.categories && this.categories.length > 0) {
                        // 使用第一个可用的分类
                        itemToSend.categoryId = this.categories[0].id;
                        console.log('添加默认分类ID:', itemToSend.categoryId);
                    } else {
                        console.error('无法确定分类ID，添加物品可能会失败');
                    }
                }

                // 确保物品数据中包含位置ID
                if (!itemToSend.locationId) {
                    // 从localStorage获取当前位置ID
                    const currentLocationId = localStorage.getItem('currentLocationId');
                    if (currentLocationId) {
                        itemToSend.locationId = parseInt(currentLocationId) || currentLocationId;
                        console.log('从localStorage获取并添加位置ID:', itemToSend.locationId);
                    } else if (this.locations && this.locations.length > 0) {
                        // 如果没有位置ID，使用第一个可用位置
                        itemToSend.locationId = this.locations[0].id;
                        console.log('使用第一个可用位置ID:', this.locations[0].id);
                    } else {
                        console.error('无法确定位置ID，添加物品可能会失败');
                    }
                }

                // 确保包含位置名称信息
                if (itemToSend.locationId && !itemToSend.specificLocation) {
                    const locationObj = this.locations.find(l => l.id === itemToSend.locationId);
                    if (locationObj) {
                        itemToSend.locationName = locationObj.name;
                        itemToSend.specificLocation = locationObj.name;
                        console.log('添加位置名称信息:', itemToSend.locationName);
                    }
                }

                const result = await itemService.createItem(itemToSend);
                console.log('itemService.createItem返回结果:', result);

                if (result.success) {
                    this.dataSource = result.source;

                    // 根据数据来源显示不同的消息
                    if (result.source === 'mock') {
                        ElMessage.warning(`无法连接到后端服务，已在本地添加物品`);
                    } else {
                        ElMessage.success('添加物品成功');

                        // 发送物品创建的消息
                        const locationName = itemToSend.locationName || itemToSend.specificLocation || '未知位置';

                        // 确保有物品ID
                        const itemWithId = {
                            ...itemToSend,
                            id: result.id
                        };

                        // 记录物品创建活动
                        messageHelper.recordItemCreated(itemWithId, locationName)
                            .catch(error => console.error('记录物品创建活动失败:', error));
                    }

                    // 刷新列表
                    await this.fetchItems();
                    return { success: true, id: result.id };
                } else {
                    // 添加失败的情况
                    ElMessage.error(result.message || '添加失败');
                    return {
                        success: false,
                        message: result.message || '添加失败',
                        source: result.source
                    };
                }
            } catch (error) {
                console.error('添加物品失败:', error);
                ElMessage.error(error.message || '添加物品失败');
                return {
                    success: false,
                    message: error.message || '添加物品失败'
                };
            }
        },

        async updateItem(id, partialUpdateData) {
            try {
                // 1. 根据 id 从 state.items 获取当前完整的物品对象
                const currentItem = this.items.find(item => item.id === id);
                if (!currentItem) {
                    console.error(`更新失败：未在store中找到ID为 ${id} 的物品。`);
                    ElMessage.error('更新物品失败：找不到物品');
                    return { success: false, message: '找不到物品' };
                }

                // 2. 创建一个基于当前完整物品的副本，然后应用部分更新
                let itemToSend = { ...currentItem, ...partialUpdateData };

                // 删除 isFavorite 字段 (如果它不应该被发送到后端)
                if ('isFavorite' in itemToSend) {
                    delete itemToSend.isFavorite;
                    console.log(`更新物品 ${id} 时从请求体中删除 isFavorite 字段`);
                }

                // 确保物品数据包含分类ID
                if (!itemToSend.categoryId) {
                    if (currentItem.categoryId) { // 从原始currentItem获取
                        itemToSend.categoryId = currentItem.categoryId;
                    } else if (this.categories && this.categories.length > 0) {
                        itemToSend.categoryId = this.categories[0].id;
                    }
                }

                // 确保物品数据中包含位置ID
                if (!itemToSend.locationId) {
                    if (currentItem.locationId) { // 从原始currentItem获取
                        itemToSend.locationId = currentItem.locationId;
                    } else {
                        const currentLocationId = localStorage.getItem('currentLocationId');
                        if (currentLocationId) {
                            itemToSend.locationId = parseInt(currentLocationId) || currentLocationId;
                        } else if (this.locations && this.locations.length > 0) {
                            itemToSend.locationId = this.locations[0].id;
                        }
                    }
                }

                // 确保包含位置名称信息 (如果后端不需要，此步骤可省略，但通常建议保持数据一致性)
                if (itemToSend.locationId && (!itemToSend.locationName || !itemToSend.specificLocation)) {
                    const locationObj = this.locations.find(l => l.id === itemToSend.locationId);
                    if (locationObj) {
                        itemToSend.locationName = locationObj.name;
                        itemToSend.specificLocation = locationObj.name; // 假设 specificLocation 和 locationName 相同
                    }
                }

                console.log(`开始更新物品 ${id}，合并后发送的完整数据:`, JSON.stringify(itemToSend));

                const result = await itemService.updateItem(id, itemToSend); // 发送完整的 itemToSend

                if (result.success) {
                    this.dataSource = result.source;
                    if (result.source === 'mock') {
                        ElMessage.warning(`无法连接到后端服务，已在本地更新物品`);
                    } else {
                        ElMessage.success('更新物品成功');
                        const locationName = itemToSend.locationName || itemToSend.specificLocation || '未知位置';
                        const updatedItemForMessage = { ...itemToSend, id: id }; // 确保ID用于消息

                        // 确定实际更新的字段，生成更准确的消息内容
                        let changeDetails = '信息';

                        // 检查更新了哪些字段
                        if (partialUpdateData) {
                            if ('quantity' in partialUpdateData) {
                                changeDetails = '库存数量';
                            } else if ('brand' in partialUpdateData) {
                                changeDetails = '品牌信息';
                            } else if ('price' in partialUpdateData) {
                                changeDetails = '价格信息';
                            } else if ('expiryDate' in partialUpdateData) {
                                changeDetails = '过期日期';
                            } else if ('purchaseDate' in partialUpdateData) {
                                changeDetails = '购买日期';
                            } else if ('purchaseChannel' in partialUpdateData) {
                                changeDetails = '购买渠道';
                            } else if ('specification' in partialUpdateData) {
                                changeDetails = '规格';
                            } else if ('status' in partialUpdateData) {
                                changeDetails = '状态';
                            } else if ('locationId' in partialUpdateData || 'specificLocation' in partialUpdateData) {
                                changeDetails = '存放位置';
                            } else if ('categoryId' in partialUpdateData) {
                                changeDetails = '分类';
                            } else if ('notes' in partialUpdateData) {
                                changeDetails = '备注';
                            } else if (Object.keys(partialUpdateData).length > 1) {
                                changeDetails = '多项信息';
                            }
                        }

                        messageHelper.recordItemUpdated(updatedItemForMessage, locationName, changeDetails)
                            .catch(error => console.error('记录物品更新活动失败:', error));
                    }
                    await this.fetchItems(); // 刷新列表
                    return { success: true };
                }
                return { success: false, message: result.message || '更新失败' };
            } catch (error) {
                console.error('更新物品失败:', error);
                ElMessage.error(error.message || '更新物品失败');
                return {
                    success: false,
                    message: error.message || '更新物品失败'
                };
            }
        },

        async deleteItem(id) {
            try {
                const result = await itemService.deleteItem(id);
                if (result.success) {
                    this.dataSource = result.source;
                    if (result.source === 'mock') {
                        ElMessage.warning(`无法连接到后端服务，已在本地删除物品`);
                    } else {
                        ElMessage.success('删除物品成功');

                        // 在删除物品前，先获取物品信息
                        const deletedItem = this.items.find(item => item.id === id);
                        if (deletedItem) {
                            const locationName = deletedItem.locationName || deletedItem.specificLocation || '未知位置';

                            // 记录物品删除活动
                            messageHelper.recordItemDeleted(deletedItem, locationName)
                                .catch(error => console.error('记录物品删除活动失败:', error));
                        } else {
                            console.warn(`无法找到ID为 ${id} 的物品信息，跳过记录删除活动`);
                        }
                    }
                    // 刷新列表
                    this.fetchItems();
                    return { success: true };
                }
                return { success: false, message: result.message || '删除失败' };
            } catch (error) {
                return {
                    success: false,
                    message: error.message || '删除物品失败'
                };
            }
        }
    }
}) 